package cn.cmkj.auction.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.AddressOfListAdapter;
import cn.cmkj.auction.app.BaseActivity;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.Address;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.widget.swipe.SwipeMenu;
import cn.cmkj.auction.widget.swipe.SwipeMenuBridge;
import cn.cmkj.auction.widget.swipe.SwipeMenuCreator;
import cn.cmkj.auction.widget.swipe.SwipeMenuItem;
import cn.cmkj.auction.widget.swipe.SwipeMenuItemClickListener;
import cn.cmkj.auction.widget.swipe.SwipeMenuRecyclerView;
import cn.cmkj.auction.widget.swipeRecyclerView.MySwipeMenuRecyclerView;

/**
 * Created by cunguoyao on 2017/8/30.
 */
@ContentView(R.layout.activity_user_address)
public class UserAddressActivity extends BaseActivity implements MySwipeMenuRecyclerView.OnLoadListener, View.OnTouchListener, View.OnClickListener {

    @ViewInject(R.id.title_back)
    private ImageButton back;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.layout_add_new)
    private RelativeLayout addNewAddress;

    @ViewInject(R.id.swipeRecyclerView)
    private MySwipeMenuRecyclerView swipeMenuRecyclerView;

    public static final String FROM = "from_page";
    public static final int FROM_MINE = 1;
    public static final int FROM_ORDER = 2;

    private int fromPage;
    private List<Address> mData;
    private AddressOfListAdapter addressAdapter;
    private boolean requesting = false;
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        fromPage = getIntent().getIntExtra(FROM, FROM_MINE);
        mData = new ArrayList<>();
        addressAdapter = new AddressOfListAdapter(this, mData, fromPage);
        swipeMenuRecyclerView.getRecyclerView().setLayoutManager(new LinearLayoutManager(this));
        //((SwipeMenuRecyclerView)swipeMenuRecyclerView.getRecyclerView()).setLongPressDragEnabled(true); // 开启拖拽。
        //((SwipeMenuRecyclerView)swipeMenuRecyclerView.getRecyclerView()).setItemViewSwipeEnabled(true); //开启滑动删除。
        swipeMenuRecyclerView.setAdapter(addressAdapter);
        swipeMenuRecyclerView.setOnLoadListener(this);
        SwipeMenuRecyclerView menuRecyclerView = ((SwipeMenuRecyclerView)swipeMenuRecyclerView.getRecyclerView());
        menuRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        menuRecyclerView.setSwipeMenuItemClickListener(menuItemClickListener);
        menuRecyclerView.smoothOpenRightMenu(0);
        menuRecyclerView.smoothOpenRightMenu(1);

        swipeMenuRecyclerView.setLoadMoreEnable(false);
        back.setOnClickListener(this);
        addNewAddress.setOnClickListener(this);
        titleText.setText("我的地址");
    }

    @Override
    protected void onResume() {
        super.onResume();
        swipeMenuRecyclerView.setRefreshing(true);
    }

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            SwipeMenuItem setDefaultItem = new SwipeMenuItem(UserAddressActivity.this)
                    .setBackground(R.color.swipe_menu_gray)// 点击的背景。
                    .setText("设为默认") // 文字。
                    .setTextSize(16) // 文字大小。
                    .setTextColor(getResources().getColor(R.color.white))
                    .setHeight(LinearLayout.LayoutParams.MATCH_PARENT)
                    .setWidth(150);
            SwipeMenuItem editItem = new SwipeMenuItem(UserAddressActivity.this)
                    .setBackground(R.color.swipe_menu_brown)// 点击的背景。
                    .setText("编辑") // 文字。
                    .setTextSize(16) // 文字大小。
                    .setTextColor(getResources().getColor(R.color.white))
                    .setHeight(LinearLayout.LayoutParams.MATCH_PARENT)
                    .setWidth(150);
            SwipeMenuItem deleteItem = new SwipeMenuItem(UserAddressActivity.this)
                    .setBackground(R.color.swipe_menu_red) // 图标。
                    .setText("删除") // 文字。
                    .setTextSize(16) // 文字大小。
                    .setTextColor(getResources().getColor(R.color.white)) // 文字颜色。
                    .setHeight(LinearLayout.LayoutParams.MATCH_PARENT)
                    .setWidth(150);
            switch (viewType) {
                case 0://默认地址
                    swipeRightMenu.addMenuItem(editItem); // 添加一个按钮到左侧菜单。
                    swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。.
                    break;
                case 1:
                    swipeRightMenu.addMenuItem(setDefaultItem); // 添加一个按钮到左侧菜单。
                    swipeRightMenu.addMenuItem(editItem); // 添加一个按钮到左侧菜单。
                    swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。.
                    break;

            }
        }
    };

    private SwipeMenuItemClickListener menuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            int menuPosition = menuBridge.getPosition();
            Address address = addressAdapter.getItem(menuBridge.getAdapterPosition());
            if(address.isDefault()) {
                switch (menuPosition) {
                    case 0:
                        menuBridge.closeMenu();
                        Intent intent = new Intent(UserAddressActivity.this, UserAddressEditActivity.class);
                        intent.putExtra("address", address);
                        startActivity(intent);
                        break;
                    case 1:
                        menuBridge.closeMenu();
                        break;
                }
            }else {
                switch (menuPosition) {
                    case 0:
                        menuBridge.closeMenu();
                        setDefaultAddress(address);
                        break;
                    case 1:
                        menuBridge.closeMenu();
                        Intent intent = new Intent(UserAddressActivity.this, UserAddressEditActivity.class);
                        intent.putExtra("address", address);
                        startActivity(intent);
                        break;
                    case 2:
                        menuBridge.closeMenu();
                        break;
                }
            }
        }
    };

    @Override
    public void onRefresh() {
        page = 1;
        LogUtil.e("--onRefresh:page=" + page);
        mData.clear();
        fetchData();
    }

    @Override
    public void onLoadMore() {
        page = page + 1;
        LogUtil.e("--onLoadMore:page=" + page);
        fetchData();
    }

    public void fetchData() {
        LogUtil.e("--fetchData");
        if(requesting)return;
        requesting = true;
        User user = getAccount();
        if(user == null) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                    Toast.makeText(UserAddressActivity.this, "您还没有登录，请先登录", Toast.LENGTH_SHORT).show();
                }
            }, 1000);
        }else {
            RequestParams params = new RequestParams(Urls.api);
            params.addParameter("method", Urls.memberAddress);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    //结束后停止刷新
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONArray jsonArray = jsonStr.optJSONArray("data");
                        List<Address> temp = Address.parseJsonArray(jsonArray);
                        mData.clear();
                        mData.addAll(temp);
                        addressAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    //结束后停止刷新
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                }

                @Override
                public void cancel(CancelledException e) {
                    //结束后停止刷新
                    requesting = false;
                    swipeMenuRecyclerView.complete();
                }
            });
        }
    }

    private void setDefaultAddress(Address address) {
        User user = getAccount();
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.saveAddress);
        params.addParameter("accesstoken", user.getToken());
        params.addParameter("member_id", user.getId());
        params.addParameter("ship_id", address.getId());
        params.addParameter("ship_name", address.getName());
        params.addParameter("ship_area", address.getArea());
        params.addParameter("ship_addr", address.getAddr());
        params.addParameter("ship_zip", address.getZip());
        params.addParameter("ship_tel", address.getTelphone());
        params.addParameter("ship_mobile", address.getMobile());
        params.addParameter("is_default", "1");
        x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
            @Override
            public void success(String s) {
                Toast.makeText(UserAddressActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
                onRefresh();
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                Toast.makeText(UserAddressActivity.this, "设置失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void cancel(CancelledException e) {

            }
        });
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (requesting) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.layout_add_new:
                Intent intent = new Intent(this, UserAddressEditActivity.class);
                startActivity(intent);
                break;
        }
    }
}
